package top.saiyin.linked;

/**
 * @Program: leetcode
 * @Description: 删除链表的倒数第N个节点
 * @Author: sy
 * @Create: 2020-08-28 09:26
 **/
public class RemoveNthNodeFromEndOfList {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        System.out.println(removeNthFromEnd(node1, 2));
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode first = dummy;
        ListNode second = dummy;
        // 当first移动到距离目标元素second的距离为N-1时
        for (int i = 1; i <= n + 1; i++) {
            first = first.next;
        }
        // 同时开始移动second。
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        // 删除节点
        second.next = second.next.next;
        return dummy.next;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }
}
